import { api_getQuestionById } from '@/api'
import { useRequest } from 'ahooks'
import { useParams } from 'react-router-dom'
import { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import { resetComponents } from '@/store/modules/componentsReducer'
import { resetPageInfo } from '@/store/modules/pageInfoReducer'

const useLoadQuestionData = () => {
  const { id = '' } = useParams()
  const dispatch = useDispatch()

  const { loading, data, error, run } = useRequest(
    async id => {
      if (!id) throw new Error('问卷id为空')
      return await api_getQuestionById(id)
    },
    {
      manual: true,
    }
  )
  useEffect(() => {
    run(id)
  }, [id])

  useEffect(() => {
    if (!data) return

    const { title = '', desc = '', js = '', css = '', componentList = [], isPublished } = data

    let selectedId = ''
    if (componentList.length > 0) {
      selectedId = componentList[0].fe_id
    }

    dispatch(resetComponents({ componentList, selectedId, copiedComponent: null }))
    dispatch(resetPageInfo({ title, desc, js, css, isPublished }))
  }, [data])

  return {
    loading,
    error,
  }
}
export default useLoadQuestionData
